{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#1  MutipIndex\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# -*- coding: utf-8 -*- \n",
    "\n",
    "import numpy as np\n",
    "from pandas import Series, DataFrame, MultiIndex\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Series的层次索引\n",
      "a  1   -1.438585\n",
      "   2    1.134335\n",
      "   3   -0.204339\n",
      "b  1    0.761522\n",
      "   2    0.558288\n",
      "   3    0.307119\n",
      "c  1    1.039618\n",
      "   2   -0.408071\n",
      "d  2   -1.728008\n",
      "   3    0.198326\n",
      "dtype: float64\n",
      "MultiIndex(levels=[[u'a', u'b', u'c', u'd'], [1, 2, 3]],\n",
      "           labels=[[0, 0, 0, 1, 1, 1, 2, 2, 3, 3], [0, 1, 2, 0, 1, 2, 0, 1, 1, 2]])\n"
     ]
    }
   ],
   "source": [
    "print 'Series的层次索引'\n",
    "data = Series(np.random.randn(10),\n",
    "              index = [['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'd', 'd'],\n",
    "                       [1, 2, 3, 1, 2, 3, 1, 2, 2, 3]])\n",
    "print data\n",
    "print data.index\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1    0.761522\n",
      "2    0.558288\n",
      "3    0.307119\n",
      "dtype: float64\n",
      "b  1    0.761522\n",
      "   2    0.558288\n",
      "   3    0.307119\n",
      "c  1    1.039618\n",
      "   2   -0.408071\n",
      "dtype: float64\n",
      "a  1   -1.438585\n",
      "   2    1.134335\n",
      "dtype: float64\n"
     ]
    }
   ],
   "source": [
    "print data.b\n",
    "print data['b':'c']\n",
    "print data[:2] #使用数字作为索引就不区分1,2级索引了，就按实际的行的索引\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false,
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "          1         2         3\n",
      "a -1.438585  1.134335 -0.204339\n",
      "b  0.761522  0.558288  0.307119\n",
      "c  1.039618 -0.408071       NaN\n",
      "d       NaN -1.728008  0.198326\n",
      "a  1   -1.438585\n",
      "   2    1.134335\n",
      "   3   -0.204339\n",
      "b  1    0.761522\n",
      "   2    0.558288\n",
      "   3    0.307119\n",
      "c  1    1.039618\n",
      "   2   -0.408071\n",
      "d  2   -1.728008\n",
      "   3    0.198326\n",
      "dtype: float64\n",
      "-------------\n",
      "a  1   -1.438585\n",
      "   2    1.134335\n",
      "   3   -0.204339\n",
      "b  1    0.761522\n",
      "   2    0.558288\n",
      "   3    0.307119\n",
      "c  1    1.039618\n",
      "   2   -0.408071\n",
      "d  2   -1.728008\n",
      "   3    0.198326\n",
      "dtype: float64\n"
     ]
    }
   ],
   "source": [
    "print data.unstack()  #就相当于第一级索引作为行索引，第二级索引作为列索引，把series展开为一个dataframe\n",
    "print data.unstack().stack()\n",
    "print \"-------------\"\n",
    "print data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "DataFrame的层次索引\n",
      "     Ohio     Colorado\n",
      "    Green Red    Green\n",
      "a 1     0   1        2\n",
      "  2     3   4        5\n",
      "b 1     6   7        8\n",
      "  2     9  10       11\n",
      "-----------------------\n",
      "state      Ohio     Colorado\n",
      "color     Green Red    Green\n",
      "key1 key2                   \n",
      "a    1        0   1        2\n",
      "     2        3   4        5\n",
      "b    1        6   7        8\n",
      "     2        9  10       11\n"
     ]
    }
   ],
   "source": [
    "print 'DataFrame的层次索引'\n",
    "frame = DataFrame(np.arange(12).reshape((4, 3)),\n",
    "                  index = [['a', 'a', 'b', 'b'], [1, 2, 1, 2]],\n",
    "                  columns = [['Ohio', 'Ohio', 'Colorado'], ['Green', 'Red', 'Green']])\n",
    "print frame\n",
    "print \"-----------------------\"\n",
    "frame.index.names = ['key1', 'key2']\n",
    "frame.columns.names = ['state', 'color']\n",
    "print frame\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "state     color\n",
      "Ohio      Green    0\n",
      "          Red      1\n",
      "Colorado  Green    2\n",
      "Name: (a, 1), dtype: int32\n",
      "-------------------------\n",
      "color\n",
      "Green    5\n",
      "Name: (a, 2), dtype: int32\n",
      "--------------------------\n",
      "4\n",
      "\n",
      "直接用MultiIndex创建层次索引结构\n",
      "MultiIndex(levels=[[u'Colorado', u'Ohio'], [u'Gree', u'Green', u'Red']],\n",
      "           labels=[[1, 1, 0], [0, 2, 1]],\n",
      "           names=[u'state', u'color'])\n"
     ]
    }
   ],
   "source": [
    "print frame.ix['a', 1]\n",
    "print \"-------------------------\"\n",
    "print frame.ix['a', 2]['Colorado']\n",
    "print \"--------------------------\"\n",
    "print frame.ix['a', 2]['Ohio']['Red']\n",
    "print\n",
    "\n",
    "print '直接用MultiIndex创建层次索引结构'\n",
    "print MultiIndex.from_arrays([['Ohio', 'Ohio', 'Colorado'], ['Gree', 'Red', 'Green']],\n",
    "                             names = ['state', 'color'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "索引层级交换\n",
      "           Ohio     Colorado\n",
      "          Green Red    Green\n",
      "key2 key1                   \n",
      "1    a        0   1        2\n",
      "2    a        3   4        5\n",
      "1    b        6   7        8\n",
      "2    b        9  10       11\n",
      "           Ohio     Colorado\n",
      "          Green Red    Green\n",
      "key1 key2                   \n",
      "a    1        0   1        2\n",
      "     2        3   4        5\n",
      "b    1        6   7        8\n",
      "     2        9  10       11\n",
      "\n",
      "根据索引排序\n",
      "           Ohio     Colorado\n",
      "          Green Red    Green\n",
      "key1 key2                   \n",
      "a    1        0   1        2\n",
      "b    1        6   7        8\n",
      "a    2        3   4        5\n",
      "b    2        9  10       11\n",
      "           Ohio     Colorado\n",
      "          Green Red    Green\n",
      "key2 key1                   \n",
      "1    a        0   1        2\n",
      "     b        6   7        8\n",
      "2    a        3   4        5\n",
      "     b        9  10       11\n"
     ]
    }
   ],
   "source": [
    "print '索引层级交换'\n",
    "frame = DataFrame(np.arange(12).reshape((4, 3)),\n",
    "                  index = [['a', 'a', 'b', 'b'], [1, 2, 1, 2]],\n",
    "                  columns = [['Ohio', 'Ohio', 'Colorado'], ['Green', 'Red', 'Green']])\n",
    "frame.index.names = ['key1', 'key2']\n",
    "\n",
    "frame_swapped = frame.swaplevel('key1', 'key2')\n",
    "print frame_swapped\n",
    "print frame_swapped.swaplevel(0, 1)\n",
    "print\n",
    "\n",
    "print '根据索引排序'\n",
    "print frame.sortlevel('key2')\n",
    "print frame.swaplevel(0, 1).sortlevel(0)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   a  b    c  d\n",
      "0  0  7  one  0\n",
      "1  1  6  one  1\n",
      "2  2  5  one  2\n",
      "3  3  4  two  0\n",
      "4  4  3  two  1\n",
      "5  5  2  two  2\n",
      "6  6  1  two  3\n",
      "       a  b\n",
      "c   d      \n",
      "one 0  0  7\n",
      "    1  1  6\n",
      "    2  2  5\n",
      "two 0  3  4\n",
      "    1  4  3\n",
      "    2  5  2\n",
      "    3  6  1\n",
      "       a  b    c  d\n",
      "c   d              \n",
      "one 0  0  7  one  0\n",
      "    1  1  6  one  1\n",
      "    2  2  5  one  2\n",
      "two 0  3  4  two  0\n",
      "    1  4  3  two  1\n",
      "    2  5  2  two  2\n",
      "    3  6  1  two  3\n",
      "     c  d  a  b\n",
      "0  one  0  0  7\n",
      "1  one  1  1  6\n",
      "2  one  2  2  5\n",
      "3  two  0  3  4\n",
      "4  two  1  4  3\n",
      "5  two  2  5  2\n",
      "6  two  3  6  1\n"
     ]
    }
   ],
   "source": [
    "\n",
    "frame1 = DataFrame({'a':range(7),\n",
    "                   'b':range(7, 0, -1),\n",
    "                   'c':['one', 'one', 'one', 'two', 'two', 'two', 'two'],\n",
    "                   'd':[0, 1, 2, 0, 1, 2, 3]})\n",
    "print frame1\n",
    "print frame1.set_index(['c', 'd'])  #把c/d列变成索引\n",
    "print frame1.set_index(['c', 'd'], drop = False) # 把c/d列变成索引，但不改变数据\n",
    "frame2 = frame1.set_index(['c', 'd'])\n",
    "print frame2.reset_index()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "arrays = [['bar', 'bar', 'baz' , 'baz', 'foo','foo','qux','qux'],\\\n",
    "          ['one', 'two','one','two','one','two','one','two']]\n",
    "\n",
    "tuples = list(zip(* arrays))\n",
    "index = MultiIndex.from_tuples(tuples, names= [ 'first', 'second'])\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
